# -*- coding: utf-8 -*-
"""
@author: hunan
@date: 2024-12-09
@description: 
"""
import logging
import os
import shutil
from datetime import datetime

import pythoncom
from win32com import client

from product_upload.util.basic.common_util import sleep_random_duration, kill_processes_by_name

logger = logging.getLogger(__name__)


def create_folder(parent_folder, date=datetime.now().strftime("%Y-%m-%d")):
    # 获取桌面路径
    desktop = os.path.join(os.path.expanduser("~"), "Desktop")
    # 拼接完整路径
    full_path = os.path.join(desktop, "amazon_file", parent_folder, f'{date}')
    # 检查文件夹是否存在，不存在则创建
    if not os.path.exists(full_path):
        os.makedirs(full_path)
    return full_path


def copy_and_rename_file_with_row_check(source_file, destination_folder, new_name, sheet_name="Template", limit=200):
    # 确保目标文件夹存在
    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)

    base_name, ext = os.path.splitext(new_name)  # 分离文件名和扩展名
    file_index = 0
    new_file_path = os.path.join(destination_folder, new_name)

    while os.path.exists(new_file_path):
        # 如果文件已存在，检查行数
        row_count = get_xlsm_row_num(new_file_path, sheet_name)
        if row_count > limit:
            # 如果行数超过limit，生成新的文件名
            file_index += 1
            new_file_path = os.path.join(destination_folder, f"{base_name}-{file_index}{ext}")
        else:
            # 如果行数不超过200，不再拷贝
            return new_file_path

    # 拷贝文件并重命名
    shutil.copy2(source_file, new_file_path)
    return new_file_path


def copy_and_rename_file(source_file, destination_folder, new_name):
    # 检查目标文件夹是否存在，不存在则创建
    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)
    new_file_path = os.path.join(destination_folder, new_name)
    shutil.copy2(source_file, new_file_path)
    return new_file_path


# 把xlsm文件写入到文件
def write_to_amazon_template_xlsm(file_path, data, sheet_name="Template", retries=3):
    wps = None
    attempt = 0
    while attempt < retries:
        try:
            pythoncom.CoInitialize()
            wps = client.Dispatch("ket.Application")
            wps.Visible = False
            workbook = wps.Workbooks.Open(file_path)
            sheet = workbook.Sheets(sheet_name)
            last_row = sheet.UsedRange.Rows.Count
            first_empty_row = last_row + 1
            # for i, row_data in enumerate(data):
            #     for j, value in enumerate(row_data):
            #         sheet.Cells(first_empty_row + i, j + 1).Value = value
            row_count = len(data)
            col_count = len(data[0]) if row_count > 0 else 0
            range_to_write = sheet.Range(sheet.Cells(first_empty_row, 1), sheet.Cells(first_empty_row + row_count - 1, col_count))
            range_to_write.Value = data  # 批量写入二维数组数据
            workbook.Save()  # 保存工作簿
            workbook.Close()  # 关闭工作簿
            break  # 成功则退出重试
        except Exception as e:
            logger.error(f"写入过程中发生错误: {e}")
            attempt += 1
            if attempt < retries:
                logger.error(f"写入xlsm重试第 {attempt} 次...")
                kill_processes_by_name("wps")
                sleep_random_duration()
        finally:
            if wps:
                wps.Quit()  # 退出WPS
            pythoncom.CoUninitialize()
            if attempt < retries:
                sleep_random_duration()


# 把价格、库存写入到txt文件中
def write_2d_list_to_txt(file_path, data):
    with open(file_path, 'w', encoding='utf-8') as file:
        for row in data:
            # 将每个元素转换为字符串，并用制表符连接
            line = '\t'.join(str(item) for item in row)
            # 写入行数据，并添加换行符
            file.write(line + '\n')


def get_xlsm_row_num(file_path, sheet_name="Template"):
    wps = None
    try:
        pythoncom.CoInitialize()
        wps = client.Dispatch("ket.Application")
        wps.Visible = False
        workbook = wps.Workbooks.Open(file_path)
        sheet = workbook.Sheets(sheet_name)  # 获取指定的工作表
        last_row = sheet.UsedRange.Rows.Count
        workbook.Save()
        workbook.Close()
        return last_row
    except Exception as e:
        logger.error(f"wps读取总行数出错: {e}")
    finally:
        if wps:
            wps.Quit()  # 退出WPS
        pythoncom.CoUninitialize()  # 释放COM资源
        sleep_random_duration()


def move_files_to_shared_folder(local_base_path=f'{os.path.join(os.path.expanduser("~"), 'Desktop')}\\amazon_file', shared_base_path=r"\\CENTER\center\file\amazon_file"):
    for root, dirs, files in os.walk(local_base_path, topdown=False):
        # 计算相对路径，以便在共享文件夹中创建相同的结构
        relative_path = os.path.relpath(root, local_base_path)
        destination_root = os.path.join(shared_base_path, relative_path)
        # 如果目标目录不存在，则创建它
        if not os.path.exists(destination_root):
            os.makedirs(destination_root)
        # 移动文件到目标位置，并记录哪些文件被成功移动
        moved_files = []
        for file in files:
            src_file = os.path.join(root, file)
            dst_file = os.path.join(destination_root, file)
            try:
                shutil.move(src_file, dst_file)  # 使用 move() 函数直接移动文件
                moved_files.append(file)
            except Exception as e:
                logger.error(f"Failed to move {src_file}: {e}")
        # 删除已经成功移动的文件
        for file in moved_files:
            src_file = os.path.join(root, file)
            if os.path.exists(src_file):
                try:
                    os.remove(src_file)
                except Exception as e:
                    logger.error(f"Failed to delete {src_file}: {e}")
        # 如果一个目录下的所有文件和子目录都被移除了，可以删除空目录
        if not os.listdir(root):
            try:
                os.rmdir(root)
            except Exception as e:
                logger.error(f"Failed to remove directory {root}: {e}")


if __name__ == "__main__":
    pass
